<?php
namespace app\home\logic;

use think\Model;

class Coupon extends Model {
    public function sendCoupon($data) {
        if (!$data['user_id']) {
            return null;
        }
        $list = model('coupon')->getList([
                'type' => $data['type'] ?: 1,
                'status' => 1,
        ]);
        foreach ($list as $key => $val) {
            model('coupon')->send([
                    'type' => $data['type'],
                    'coupon_id' => $val['id'],
                    'user_id' => $data['user_id'],
                    'mark' => $data['mark']
            ]);
        }
        return true;
    }

    //获取用户红包列表
    function getList($data = array()){
        $prefix = config('database.prefix');
        $_sql = " where 1=1 ";
        $_select = " p1.*,p2.username as username,p3.name as coupon_name,p3.title as coupon_title,p3.money,p3.min,p3.min_day,p3.style,p3.interest,p3.max";
        $_order = " order by p1.addtime desc";
        $sql = "select SELECT from `{$prefix}coupon_users` as p1
              left join `{$prefix}users` as p2 on p2.user_id=p1.user_id
              left join `{$prefix}coupon` as p3 on p3.id=p1.coupon_id SQL ORDER LIMIT ";
        if (isset($data['id'])) {
            $_sql .= " and p1.id =  '{$data['id']}'";
        }
        if (isset($data['user_id'])) {
            $_sql .= " and p1.user_id = '{$data['user_id']}'";
        }
        if (isset($data['style'])) {
            $_sql .= " and p3.style = '{$data['style']}'";
        }
        if (isset($data['status']) && $data['status'] !="") {
            if($data['status'] == "0") {
                $_sql .= " and p1.status = 1 and p1.exptime != 0 and p1.exptime <".time();
            } elseif($data['status'] == "1") {
                $_sql .= " and p1.status = 1 and (p1.exptime = 0 or p1.exptime >=".time().")";
            } elseif($data['status'] == "3") {
                $_sql .= " and ((p1.status = '2' and p1.borrow_tender_id>0) or p1.status = '{$data['status']}')";
            } else{
                $_sql .= " and p1.status = '{$data['status']}'";
            }
        } else {
            $_sql .= " and p1.status = 1 and (p1.exptime = 0 or p1.exptime >=".time().")";
        }
        if (isset($data['borrow_type'])) {
            $_sql .= " and (p3.borrow_type = '{$data['borrow_type']}' or p3.borrow_type ='all') ";
        }
        if (isset($data['borrow_nid'])) {
            $_sql .= " and (p3.borrow_nid = '{$data['borrow_nid']}' or p3.borrow_nid ='all') ";
        }
        if (isset($data['style']) && ($data['style'] == '0' || $data['style'] == '1')) {
            $_sql .= " and p3.style = '{$data['style']}'";
        }
        if (isset($data['money'])) {
            $_sql .= " and p3.min <= '{$data['money']}'";
        }
        if (isset($data['min_day'])) {
            $_sql .= " and p3.min_day <= '{$data['min_day']}'";
        }
        if (isset($data['username'])) {
            $_sql .= " and p2.username = '{$data['username']}'";
        }
        if(isset($data['order'])){
            $_order = $data['order'];
        }

        //分页返回结果
        $data['page'] = isset($data['page'])?:1;
        $data['epage'] = isset($data['epage'])?:10;
        $_limit = " limit ".($data['epage'] * ($data['page'] - 1)).", {$data['epage']}";

        if (isset($data['limit'])){
            if ($data['limit'] != "all"){
                $_limit = "  limit ".$data['limit'];
            } else {
                $_limit = "";
            }
        }

        $list_sql = str_replace(array('SELECT', 'SQL','ORDER', 'LIMIT'), array($_select,$_sql,$_order, $_limit), $sql);
        $list = db()->query($list_sql);
        foreach ($list as $key => $value) {
            if($list[$key]["exptime"] != 0 && $list[$key]["exptime"] < time()  && $list[$key]["status"] == "1"){ //已过期
                $list[$key]["status"] = "0";
            }
        }
        return $list;
    }

    //获取用户红包数量
    function getCount($data = array()){
        $prefix = config('database.prefix');
        $_sql = " where 1=1 ";
        $sql = "select count(*) total from `{$prefix}coupon_users` as p1
              left join `{$prefix}users` as p2 on p2.user_id=p1.user_id
              left join `{$prefix}coupon` as p3 on p3.id=p1.coupon_id";
        if (isset($data['id'])) {
            $_sql .= " and p1.id =  '{$data['id']}'";
        }
        if (isset($data['user_id'])) {
            $_sql .= " and p1.user_id = '{$data['user_id']}'";
        }
        if (isset($data['style'])) {
            $_sql .= " and p3.style = '{$data['style']}'";
        }
        if (isset($data['status']) && $data['status'] !="") {
            if($data['status'] == "0") {//已过期
                $_sql .= " and p1.status = 1 and p1.exptime != 0 and p1.exptime <".time();
            } elseif($data['status'] == "1") {//可使用
                $_sql .= " and p1.status = 1 and (p1.exptime = 0 or p1.exptime >=".time().")";
            } elseif($data['status'] == "3") {//已使用
                $_sql .= " and ((p1.status = '2' and p1.borrow_tender_id>0) or p1.status = '{$data['status']}')";
            } else{
                $_sql .= " and p1.status = '{$data['status']}'";
            }
        } else {
            $_sql .= " and p1.status = 1 and (p1.exptime = 0 or p1.exptime >=".time().")";
        }
        if (isset($data['borrow_type'])) {
            $_sql .= " and (p3.borrow_type = '{$data['borrow_type']}' or p3.borrow_type ='all') ";
        }
        if (isset($data['borrow_nid'])) {
            $_sql .= " and (p3.borrow_nid = '{$data['borrow_nid']}' or p3.borrow_nid ='all') ";
        }
        if (isset($data['style']) && ($data['style'] == '0' || $data['style'] == '1')) {
            $_sql .= " and p3.style = '{$data['style']}'";
        }
        if (isset($data['money'])) {
            $_sql .= " and p3.min <= '{$data['money']}'";
        }
        if (isset($data['min_day'])) {
            $_sql .= " and p3.min_day <= '{$data['min_day']}'";
        }
        if (isset($data['username'])) {
            $_sql .= " and p2.username = '{$data['username']}'";
        }
        $result = db()->query($sql . $_sql);
        if (!$result) {
            return 0;
        } else {
            return $result[0]['total'];
        }
    }

    function UseCouponUsers($data = []){
        if (!isset($data['id'])) return null;
        if (!isset($data['borrow_nid'])) return null;
        if (!isset($data['borrow_tender_id'])) return null;

        $result = db('coupon_users')->where(['id' => $data['id']])->find();
        if (!$result) return null;
        if ($result["status"]=="0" || $result["exptime"] <= time()) return null;
        if ($result["status"]=="2" || $result["status"]=="3") return null;
        if ($result["user_id"]!=$data['user_id']) return null;

        $borrow_result = db('borrow')->where(['borrow_nid' => $data['borrow_nid']])->find();
        $borrow_tender_result = db('borrow_tender')->where(['id' => $data['borrow_tender_id']])->find();
        $coupon_result = db('coupon')->where(['id' => $result['coupon_id']])->find();

        if($data['account']<$coupon_result['min'] || ($data['account']>$coupon_result['max'] && $coupon_result['max']>0)){
            return false;
        }

        if(($coupon_result['borrow_type'] == 'all' || $borrow_result['borrow_type']==$coupon_result['borrow_type'])
                && ($coupon_result['borrow_nid'] == 'all' || $borrow_result['borrow_nid']==$coupon_result['borrow_nid'])) {

            if ($borrow_result["borrow_type"] == "day" || $borrow_result["borrow_type"] == "second") {
                $min_day = intval($borrow_result["borrow_period"]);
            } else {
                $min_day = intval($borrow_result["borrow_period"]) * 30;
            }
            if($min_day >=  $coupon_result['min_day'] && $borrow_tender_result["account_tender"] >= $coupon_result['min']) {

                //开始使用
                $re = model('coupon_users')->edit(['id' => $data['id']], [
                        'status' => 2,
                        'borrow_nid' => $data['borrow_nid'],
                        'borrow_tender_id' => $data['borrow_tender_id']
                ]);
                if (!$re) return null;
                //使用数量+1
                $re = db('coupon')->where(['id' => $result['coupon_id']])->setInc('usednum');
                if (!$re) return null;
                return $coupon_result;
            }
        }
        return false;

    }
}
